package com.md.application.service.users;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.md.api.authentication.UsersApi;
import com.md.application.assembler.UsersAssembler;
import com.md.domain.service.AuthenticationDomainService;
import com.md.exception.ServerException;
import com.md.model.bo.ServiceContextBo;
import com.md.model.po.Users;
import com.md.model.request.IdRequest;
import com.md.model.request.authentication.users.AddUsersRequest;
import com.md.model.request.authentication.users.LoginRequest;
import com.md.model.request.authentication.users.RegisterUsersRequest;
import com.md.model.request.authentication.users.UpdateUsersRequest;
import com.md.model.response.authentication.users.RegisterUsersResponse;
import com.md.model.response.authentication.users.UsersLoginResponse;
import com.md.model.response.authentication.users.UsersResponse;
import com.md.model.system.CommonResult;
import com.md.util.ClassUtils;
import com.md.util.HttpUtils;
import com.md.value.enums.ErrorEnum;
import lombok.RequiredArgsConstructor;
import org.dom4j.DocumentException;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.util.Base64;

/**
 * @author 刘骄阳
 * 2022-04-01 18:30
 */
@Service
@RequiredArgsConstructor
public class UsersApplicationService implements UsersApi {
  private static final String AUTHORITY = "https://login.microsoftonline.com/00618cc4-0e79-43ef-9df6-41ddc9a38d62/";
  private static final String CLIENT_SECRET = "7ebe354a-b057-496d-a309-6182be4ccc15";
  private static final String CLIENT_ID = "ccaadf4b-5546-4077-9a30-75a23261ec57";
  private final AuthenticationDomainService authenticationDomainService;
  @JsonIgnore
  private final Environment environment;

  @Override
  public CommonResult<String> demo() throws URISyntaxException, MalformedURLException {
    HttpServletRequest request = HttpUtils.getHttpServletRequest();
    HttpServletResponse response = HttpUtils.getHttpServletResponse();
    // 使用OpenSAML或其他库初始化SP配置
//
//    IClientCredential credential = ClientCredentialFactory.createFromSecret(CLIENT_SECRET);
//    InteractiveRequestParameters parameters = InteractiveRequestParameters
//        .builder(new URI("http://localhost"))
//        .scopes(Sets.newHashSet())
//        .build();
//    PublicClientApplication publicClientApplication =
//        PublicClientApplication
//            .builder(CLIENT_ID)
//            .authority(AUTHORITY)
//            .build();
//
//    IAuthenticationResult result = publicClientApplication.acquireToken(parameters).join();
    System.out.println();
    return null;
  }

  @Override
  public CommonResult<Long> responses() throws MalformedURLException, URISyntaxException, DocumentException {
    HttpServletRequest httpServletRequest = HttpUtils.getHttpServletRequest();
    String samlResponse = httpServletRequest.getParameter("SAMLResponse");
    String xmlString = new String(Base64.getDecoder().decode(samlResponse));
    try {
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

      // 将XML字符串转换为InputSource对象
      InputSource source = new InputSource(new StringReader(xmlString));
      Document doc = dBuilder.parse(source);

      // 文档加载完成后，可进行节点查询
      doc.getDocumentElement().normalize();

      NodeList responseNodeList = doc.getElementsByTagName("samlp:Response");
      if (responseNodeList.getLength() > 0) {
        Element responseElement = (Element) responseNodeList.item(0);

        // 解析响应中的属性和元素
        String id = responseElement.getAttribute("ID");
        String version = responseElement.getAttribute("Version");
        String issueInstant = responseElement.getAttribute("IssueInstant");

        System.out.println("ID: " + id);
        System.out.println("Version: " + version);
        System.out.println("Issue Instant: " + issueInstant);

        // 进一步解析其他元素，如Issuer、Status、Assertion等
        // ...
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 添加用户
   *
   * @param request 用户请求实体
   * @return 操作结果
   */
  @Override
  public CommonResult<Long> insert(final AddUsersRequest request) {
    Users users = authenticationDomainService.register(request.getName(), request.getPassword(), request.getHeadIcon(),
      request.getPhone(), null, request.getSex());
    return CommonResult.success(users.getId());
  }

  /**
   * 注册
   *
   * @param request 用户请求实体
   * @return 响应实体
   */
  @Override
  public CommonResult<RegisterUsersResponse> register(final RegisterUsersRequest request) {
    UsersAssembler.judgeRegisterRequest(request);
    Users users = authenticationDomainService.register(request.getName(), request.getPassword(), request.getHeadIcon(),
      request.getPhone(), request.getCode(), null);
    RegisterUsersResponse response = ClassUtils.source2Target(users, RegisterUsersResponse.class);
    response.setPassword(null);
    return CommonResult.success(response);
  }


  /**
   * 手机号登录
   *
   * @param request 用户请求实体
   * @return 操作结果
   */
  @Override
  public CommonResult<UsersLoginResponse> login(final LoginRequest request) {
    UsersAssembler.judgeLoginRequest(request);
    UsersLoginResponse users;
    switch (request.getLoginMethod()) {
      case ACCOUNT_PASSWORD:
        users = authenticationDomainService.accountPasswordLogin(request.getAccount(), request.getPassword());
        break;
      case PHONE_CODE:
        users = authenticationDomainService.phoneCodeLogin(request.getPhone(), request.getCode());
        break;
      case PHONE_PASSWORD:
        users = authenticationDomainService.phonePasswordLogin(request.getPhone(), request.getPassword());
        break;
      default:
        users = null;
        break;
    }
    return CommonResult.success(users);
  }

  /**
   * 修改当前用户
   *
   * @param request 用户请求实体
   * @return 操作结果
   */
  @Override
  public CommonResult<Void> updateSelf(final UpdateUsersRequest request) {
    ServiceContextBo serviceContextBo = ServiceContextBo.buildServiceContextBo();
    request.setId(serviceContextBo.getUserId());
    authenticationDomainService.update(UsersAssembler.buildUpdatePo(request));
    return CommonResult.success();
  }

  /**
   * 修改用户信息
   *
   * @param request 用户请求实体
   * @return 操作结果
   */
  @Override
  public CommonResult<Void> updateOther(final UpdateUsersRequest request) {
    if (ObjectUtils.isEmpty(request.getId())) {
      throw ServerException.build(ErrorEnum.USER_NOT_EXISTS);
    }
    authenticationDomainService.update(UsersAssembler.buildUpdatePo(request));
    return CommonResult.success();
  }

  /**
   * 查询用户信息
   *
   * @param request 用户请求实体
   * @return 操作结果
   */
  @Override
  public CommonResult<UsersResponse> queryUserInfo(final IdRequest request) {
    if (ObjectUtils.isEmpty(request.getId())) {
      request.setId(ServiceContextBo.buildServiceContextBo().getUserId());
    }
    UsersResponse response = authenticationDomainService.queryUserInfo(request.getId());
    return CommonResult.success(response);
  }
}
